import re

import requests

from stealer import config
from . import BaseAdapter

headers = {
    "user-agent": config.USER_AGENT
}

info_headers = {
    "accept": "*/*",
    "accept-encoding": "gzip, deflate",
    "sec-fetch-dest": "empty",
    "sec-fetch-mode": "cors",
    "sec-fetch-site": "same-origin",
    "user-agent": config.USER_AGENT
}

download_headers = {
    "accept": "*/*",
    "accept-encoding": "identity;q=1, *;q=0",
    "accept-language": "zh-CN,zh;q=0.9,ja;q=0.8,en;q=0.7,zh-TW;q=0.6,de;q=0.5,fr;q=0.4,ca;q=0.3,ga;q=0.2",
    "range": "bytes=0-",
    "sec-fetch-dest": "video",
    "sec-fetch-mode": "no-cors",
    "sec-fetch-site": "cross-sit",
    "user-agent": config.USER_AGENT
}


class HuoShanAdapter(BaseAdapter):

    @classmethod
    def get_prefix_pattern(cls) -> str:
        return 'huoshan.com/hotsoon/s\/'

    @classmethod
    def make_url(cls, index) -> str:
        return f'https://share.huoshan.com/hotsoon/s/{index}'

    def index(self, url):
        index = re.findall(r'(?<=s\/)\w+', url)

        try:
            return index[0]
        except ValueError:
            return None

    def parse(self, url=None, header: bool = True):
        res = requests.get(url, headers=headers)

        try:
            iid = re.findall(r"(?<=item_id=)\d+(?=\&)", res.url)[0]
        except ValueError:
            return res.reason

        url = f"https://share.huoshan.com/api/item/info?item_id={iid}"
        res = requests.get(url, headers=info_headers)

        try:
            vid = re.findall(r'(?<=video_id\=)\w+(?=\&)', str(res.text))[0]
        except ValueError:
            return res.reason

        link = f"https://api.huoshan.com/hotsoon/item/video/_source/?video_id={vid}&line=0&app_id=0&vquality=normal"
        data = {
            'link': link,
            'name': 'name',
            'meta': {
                'headers': download_headers
            }}
        return data


if __name__ == '__main__':
    HuoShanAdapter().fetch('http://share.huoshan.com/hotsoon/s/eVDEDNYXu78')
    HuoShanAdapter().stream('http://share.huoshan.com/hotsoon/s/eVDEDNYXu78')
